package chat;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class ChatClient extends JFrame implements ActionListener{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final int WIDTH=600;
	private static final int HEIGHT=500;
	private JTextArea jtArea;
	private JButton send;
	private JTextField input;
	private Socket socket;
	public ChatClient() {
		setSize(WIDTH, HEIGHT);
		setTitle("聊天室_客户端");
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
		setLocation((screenSize.width-WIDTH)/2, (screenSize.height-HEIGHT)/2);
		jtArea=new JTextArea();
		jtArea.setEditable(false);
		add(jtArea, BorderLayout.CENTER);
		jtArea.setForeground(Color.white);
		jtArea.setBackground(Color.getHSBColor(40.77f, 0.06f, 0.50f));
		jtArea.setFont(new Font("微软雅黑", Font.BOLD, 20));
		JPanel jp=new JPanel();
		jp.setLayout(new BorderLayout());
		add(jp, BorderLayout.SOUTH);
		send=new JButton("发送");
		send.setForeground(Color.DARK_GRAY);
		send.setBackground(Color.white);
		send.addActionListener(this);
		jp.add(send, BorderLayout.EAST);
		input=new JTextField();
		jp.add(input, BorderLayout.CENTER);		
		input.setBackground(Color.getHSBColor(44f, 0.06f, 0.90f));
		try {
			socket=new Socket("localhost", 2828);
			ReceiveThread rt=new ReceiveThread(socket, jtArea);
			Thread th=new Thread(rt);
			th.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
		
		@Override
		public void run() {
			new ChatClient();
		}
	});	
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		try {
			ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
			String mess=input.getText();
			oos.writeObject(mess);
			oos.flush();
			input.setText("");
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
}
